<template>
  <div class="chatbox">
    <div class="mui-content" id="contentwrapper" style="padding-bottom: 51px;">
      <div id="msg-list">
        <span class="msg-item-time msg-more" v-show="checkLength(msgTmp)" @click="getMore">查看更多</span>
        <div class="myCell" v-for="(item,index) in msgTmp" :key="index">
          <span class="msg-item-time">{{item.replyTime}}</span>
          <div
            class="msg-item"
            msg-type="text"
            :msg-content="item.replyContent"
            v-if="item.replyType == 'doctor' && item.replyContentType == 'text'"
          >
            <img
              :src="doctor.header?doctor.header:docImg"
              class="msg-user-img"
              @error="$event.target.src=docImg"
            />
            <div class="msg-content">
              <div class="name">{{item.replyUserName}}</div>
              <div class="msg-content-inner">
                <span class="textcontent">{{item.replyContent}}</span>
              </div>
              <div class="msg-content-arrow"></div>
              <!--<span class="mui-spinner"></span>-->
            </div>
            <div class="mui-item-clear"></div>
          </div>

          <div
            class="msg-item"
            msg-type="image"
            :msg-content="item.replyContent"
            v-if="item.replyType == 'doctor' && item.replyContentType == 'image'"
          >
            <!--<img class="msg-user-img" src="../images/logo.gif" alt="" />-->
            <img
              :src="doctor.header?doctor.header:docImg"
              class="msg-user-img"
              @error="$event.target.src=docImg"
            />
            <div class="msg-content">
              <div class="name">{{item.replyUserName}}</div>
              <div class="msg-content-inner">
                <img class="msg-content-image" :src="item.replyContent" style="max-width: 100px;" />
              </div>
              <div class="msg-content-arrow"></div>
              <!--<span class="mui-spinner"></span>-->
            </div>
            <div class="mui-item-clear"></div>
          </div>

          <div
            class="msg-item msg-item-self"
            msg-type="text"
            :msg-content="item.replyContent"
            v-if="item.replyType == 'user' && item.replyContentType == 'text'"
          >
            <img
              :src="personImg?personImg:bannerImg"
              class="msg-user-img msg-user"
              @error="$event.target.src=bannerImg"
            />
            <div class="msg-content">
              <div class="name">{{item.replyUserName}}</div>
              <div class="msg-content-inner">
                <span class="textcontent">{{item.replyContent}}</span>
              </div>
              <div class="msg-content-arrow"></div>
            </div>
            <div class="mui-item-clear"></div>
          </div>

          <div
            class="msg-item msg-item-self"
            msg-type="image"
            :msg-content="item.replyContent"
            v-if="item.replyType == 'user' && item.replyContentType == 'image'"
          >
            <!-- <img class="msg-user-img msg-user" src="https://www.baidu.com/img/bd_logo1.png" alt=""> -->
            <img
              :src="personImg?personImg:bannerImg"
              class="msg-user-img msg-user"
              @error="$event.target.src=bannerImg"
            />
            <div class="msg-content">
              <div class="name">{{item.replyUserName}}</div>
              <div class="msg-content-inner">
                <img class="msg-content-image" :src="item.replyContent" style="max-width: 100px;" />
              </div>
              <div class="msg-content-arrow"></div>
            </div>
            <div class="mui-item-clear"></div>
          </div>
        </div>
      </div>
      <div class="mui-item-clear"></div>
    </div>
    <!-- <footer style="height: 51px;">
            <div class="footer-left">
                <input type="file" name="upload" id="avatar_load" ref="upload" @change="uploadimg" accept="image/*" style="display:none;" />
                <i id="msg-image" class="mui-icon mui-icon-camera" style="font-size: 28px;" @click="selectImg"></i>
            </div>
            <div class="footer-center">
                <textarea id="msg-text" type="text" class="input-text" v-model="myMsg"></textarea>
                <button id="msg-sound" type="button" class="input-sound" style="display: none;">按住说话</button>
            </div>
            <label for="" class="footer-right">
                <i id="msg-type" class="mui-icon mui-icon-mic mui-icon-paperplane" for="msg-text" @click="sendData(myMsg,'text')"></i>
            </label>
    </footer>-->
  </div>
</template>

<script>
import bannerImg from "../../assets/images/default-photo.png";
import docImg from "../../assets/images/head_images.png";
import { commonAjaxJson, RESTFUL_API } from "../../api/api";
import { doImgUpload } from "@/api/api";
import EXIF from "exif-js"; //用于获取拍摄图片的基本信息（例如：拍摄方向）
export default {
  props: ["tdata"],
  data() {
    return {
      msgTmp: [],
      bannerImg: bannerImg,
      docImg: docImg,
      // msgTmp: {
      //     "replyId": 1,
      //     "consultId": 1,
      //     "replyType": "user",
      //     "replyObjId": "",
      //     "replyUserName": "",
      //     "replyContentType": "",
      //     "replyContent": "",
      //     "replyTime": "",
      //     "readFlag": 0
      // },
      doctor: {},
      myMsg: "",
      personImg: ""
    };
  },
  watch: {
    tdata(val) {
      if (val.consultId) {
        this.loadData();
      }
    }
  },
  methods: {
    checkLength(arr) {
      if (arr && arr.length >= 10) {
        return true;
      } else {
        return false;
      }
    },
    getMore() {
      this.getLast();
      this.getFirst();
    },
    getFirst() {
      var replayId = this.msgTmp[this.msgTmp.length - 1]
        ? this.msgTmp[this.msgTmp.length - 1].replyId
        : "";
      var param = {
        consultId: this.tdata.consultId,
        replyId: replayId,
        lessOrGreater: 2
      };
      commonAjaxJson(RESTFUL_API.queryTalkList, param).then(res => {
        if (res && res.data) {
          if (res.data.data.length > 0) {
            this.msgTmp = this.msgTmp.concat(res.data.data);
          }
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: "服务器内部错误!"
          });
        }
      });
    },
    selectImg() {
      this.$refs.upload.click();
    },
    loadData() {
      var param = {
        consultId: this.tdata.consultId
      };
      commonAjaxJson(RESTFUL_API.queryTalkList, param).then(res => {
        if (res && res.data.data) {
          this.msgTmp = res.data.data;
          this.doctor = res.doctor;
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: "服务器内部错误!"
          });
        }
      });
    },
    sendData(val, valkind) {
      var param = {
        consultId: this.tdata.consultId,
        replyType: "user",
        replyContentType: valkind,
        replyContent: val
      };
      if (!val) {
        this.$store.commit("UPDATE_TOAST", {
          message: "发送消息不能为空!"
        });
        return false;
      }
      commonAjaxJson(RESTFUL_API.queryReply, param).then(res => {
        if (res) {
          this.loadData();
          this.myMsg = "";
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: "服务器内部错误!"
          });
        }
      });
    },
    //上传处理图片
    compress(file, item) {
      
      const vm = this;
      var reader = new FileReader();
      reader.onload = function(e) {
        var image = new Image();
        image.src = e.target.result;
        image.onload = function() {
          // 图片原始尺寸
          var originWidth = this.naturalWidth;
          var originHeight = this.naturalHeight;
          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          var maxWidth = 500,
            maxHeight = 500;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过400x400的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          // 缩放图片需要的canvas
          var canvas = document.createElement("canvas");
          var context = canvas.getContext("2d");
          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 获取图片的拍摄方向（通过Exit.js 插件）
          let orient;
          EXIF.getData(image, () => {
            orient = EXIF.getTag(this, "Orientation");
          });
          // 因为ios手机拍摄上传的图片会出现旋转的hack，这里需要特殊处理
          // 如果图片顺时针旋转了90度则调整下
          if (orient === 6) {
            canvas.width = targetHeight;
            canvas.height = targetWidth;
            context.rotate(Math.PI / 2);
            // (0,-imgHeight) 从旋转原理图那里获得的起始点
            context.drawImage(
              this,
              0,
              -targetHeight,
              targetWidth,
              targetHeight
            );
          } else if (orient === 3) {
            context.rotate(Math.PI);
            context.drawImage(
              this,
              -targetWidth,
              -targetHeight,
              targetWidth,
              targetHeight
            );
          } else if (orient === 8) {
            canvas.width = targetHeight;
            canvas.height = targetWidth;
            context.rotate((3 * Math.PI) / 2);
            // (0,-imgHeight) 从旋转原理图那里获得的起始点
            context.drawImage(this, -targetWidth, 0, targetWidth, targetHeight);
          } else {
            // 图片压缩
            context.drawImage(this, 0, 0, targetWidth, targetHeight);
          }
          //压缩后的图片base64 url
          vm.newUrl = canvas.toDataURL("image/jpeg");
          vm.$store.commit("HIDE_LOADING");
          vm.$set(item, "src", vm.newUrl); //生成预览地址
          vm.getUpload(item);
        };
      };
      reader.readAsDataURL(file);
    },
    // dataUrl转为blob对象，用于formdata数据提交
    dataURItoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), //base-64编码过的字符串进行解码
        n = bstr.length,
        u8arr = new Uint8Array(n); //8 位无符号整数值的类型化数组
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
    getUpload(obj) {
      let formData = new FormData();
      var blob = this.dataURItoBlob(obj["src"]);
      formData.append("files", blob);
      formData.append("fileType", "image");

      doImgUpload(formData).then(res => {
        this.sendData(res.url, "image");
      });
    },

    uploadimg() {
      let load = document.getElementById("avatar_load");
      let file = load.files;

      let reader = new FileReader();
      var obj = {
        file: file[0],
        src: ""
      };
      this.compress(file[0], obj);
    }
  },
  mounted() {
    this.personImg = JSON.parse(sessionStorage.getItem("person"))
      ? JSON.parse(sessionStorage.getItem("person")).header
      : "";
  }
};
</script>

<style lang="less" scoped>
@import "../../common/css/flex.css";
@import "../../common/css/component";
@font-face {
  font-family: Muiicons;
  font-weight: 400;
  font-style: normal;
  src: url(../../assets/fonts/mui.ttf) format("truetype");
}

.chatbox {
  width: 100%;
  // min-height: 100%;
  border-top: 1px solid #e8e8e8;
  audio {
    display: inline-block;
    vertical-align: baseline;
  }
  img {
    border: 0;
  }
  .mui-content {
    background-color: #fff;
    -webkit-overflow-scrolling: touch;
  }
  .mui-icon {
    font-family: Muiicons;
    font-size: 24px;
    font-weight: 400;
    font-style: normal;
    line-height: 1;
    display: inline-block;
    text-decoration: none;
    -webkit-font-smoothing: antialiased;
  }
  .mui-icon-mic:before {
    content: "\e302";
  }
  .mui-icon-refreshempty:before {
    content: "\e461";
  }
  /*! CSS Used from: Embedded */
  .mui-content {
    min-height: 10vh;
    padding: 0px 0px 50px 0px;
    webkit-overflow-scrolling: touch;
    margin: 0;
  }
  #msg-list {
    padding-top: 10px;
    webkit-overflow-scrolling: touch;
    min-height: 100%;
  }
  .msg-item {
    padding: 8px;
    clear: both;
  }
  .msg-item .mui-item-clear {
    clear: both;
  }
  .msg-item .msg-user {
    width: 46px;
    height: 46px;
    border: solid 1px #d3d3d3;
    display: inline-block;
    background: #fff;
    vertical-align: top;
    text-align: center;
    float: left;
    // padding: 3px;
    color: #ddd;
  }
  .msg-item .msg-user-img {
    width: 46px;
    height: 46px;
    display: inline-block;
    border-radius: 50%;
    vertical-align: top;
    text-align: center;
    float: left;
    color: #ddd;
  }
  .msg-item .msg-content {
    .name {
      font-size: 12px;
      color: #333;
    }
    display: inline-block;
    color: #333;
    vertical-align: top;
    font-size: 14px;
    position: relative;
    margin: 0px 8px;
    max-width: 65%;
    min-width: 35px;
    float: left;
  }
  .msg-item .msg-content .msg-content-inner .textcontent {
    white-space: pre-wrap;
    word-break: break-all;
  }
  .msg-item .msg-content .msg-content-inner {
    display: block;
    width: 100%;
    padding: 5px;
    border-radius: 5px;
    background-color: white;
    border: solid 1px #f1f1f1;
    height: 100%;
  }
  .msg-item .msg-content .msg-content-arrow {
    position: absolute;
    border: solid 1px #f1f1f1;
    border-right: none;
    border-top: none;
    background-color: #ffffff;
    width: 10px;
    height: 10px;
    left: -5px;
    top: 28px;
    -webkit-transform: rotateZ(45deg);
    transform: rotateZ(45deg);
  }
  .msg-item-self .msg-user,
  .msg-item-self .msg-content {
    float: right;
  }
  .msg-item-resend {
    float: right;
    width: 38px;
    height: 38px;
    line-height: 38px;
    border: solid 1px #d3d3d3;
    display: inline-block;
    background: #fff;
    border-radius: 3px;
    vertical-align: top;
    text-align: center;
    color: #ddd;
  }
  .msg-item-resend.msg-item-sending i {
    -webkit-transform-origin: 50%;
    transform-origin: 50%;
    -webkit-animation: spinner-spin 1s step-end infinite;
    animation: spinner-spin 1s step-end infinite;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
  }
  .msg-item-self .msg-content .msg-content-arrow {
    left: auto;
    right: -5px;
    -webkit-transform: rotateZ(225deg);
    transform: rotateZ(225deg);
  }
  .msg-item-self .msg-content,
  .msg-item-self .msg-content .msg-content-arrow {
    background-color: #d5f6e4;
    color: #fff;
    border-color: #afe6c8;
  }
  .msg-item.msg-item-self .msg-content .msg-content-inner {
    display: block;
    width: 100%;
    padding: 8px;
    border-radius: 5px;
    background-color: #d5f6e4;
    border: solid 1px #afe6c8;
    color: #333;
    height: 100%;
  }
  .msg-item-time {
    margin: 10px auto 0px auto;
    width: 130px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    border-radius: 3px;
    display: block;
    font-size: 12px;
    color: #999;
  }
  .msg-more {
    color: #777;
  }
  .msg-item.msg-item-self .msg-content {
    background-color: #fff;
    margin-top: -5px;
    .name {
      text-align: right;
    }
  }
  .msg-content-image {
    display: block;
  }
  /*! CSS Used keyframes */
  @-webkit-keyframes spinner-spin {
    0% {
      -webkit-transform: rotate(0deg);
    }
    8.33333333% {
      -webkit-transform: rotate(30deg);
    }
    16.66666667% {
      -webkit-transform: rotate(60deg);
    }
    25% {
      -webkit-transform: rotate(90deg);
    }
    33.33333333% {
      -webkit-transform: rotate(120deg);
    }
    41.66666667% {
      -webkit-transform: rotate(150deg);
    }
    50% {
      -webkit-transform: rotate(180deg);
    }
    58.33333333% {
      -webkit-transform: rotate(210deg);
    }
    66.66666667% {
      -webkit-transform: rotate(240deg);
    }
    75% {
      -webkit-transform: rotate(270deg);
    }
    83.33333333% {
      -webkit-transform: rotate(300deg);
    }
    91.66666667% {
      -webkit-transform: rotate(330deg);
    }
    100% {
      -webkit-transform: rotate(360deg);
    }
  }
  @keyframes spinner-spin {
    0% {
      transform: rotate(0deg);
    }
    8.33333333% {
      transform: rotate(30deg);
    }
    16.66666667% {
      transform: rotate(60deg);
    }
    25% {
      transform: rotate(90deg);
    }
    33.33333333% {
      transform: rotate(120deg);
    }
    41.66666667% {
      transform: rotate(150deg);
    }
    50% {
      transform: rotate(180deg);
    }
    58.33333333% {
      transform: rotate(210deg);
    }
    66.66666667% {
      transform: rotate(240deg);
    }
    75% {
      transform: rotate(270deg);
    }
    83.33333333% {
      transform: rotate(300deg);
    }
    91.66666667% {
      transform: rotate(330deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
  /*! CSS Used fontfaces */
  footer {
    display: block;
  }
  button,
  textarea {
    font: inherit;
    margin: 0;
    color: inherit;
  }
  button {
    overflow: visible;
  }
  button {
    text-transform: none;
  }
  button {
    cursor: pointer;
    -webkit-appearance: button;
  }
  textarea {
    overflow: auto;
  }
  button {
    font-size: 14px;
    font-weight: 400;
    line-height: 1.42;
    position: relative;
    display: inline-block;
    margin-bottom: 0;
    padding: 6px 12px;
    cursor: pointer;
    -webkit-transition: all;
    transition: all;
    -webkit-transition-timing-function: linear;
    transition-timing-function: linear;
    -webkit-transition-duration: 0.2s;
    transition-duration: 0.2s;
    text-align: center;
    vertical-align: top;
    white-space: nowrap;
    color: #333;
    border: 1px solid #ccc;
    border-radius: 3px;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 3px;
    background-color: #fff;
    background-clip: padding-box;
  }
  button:enabled:active {
    color: #fff;
    background-color: #929292;
  }
  button:disabled {
    opacity: 0.6;
  }
  textarea {
    font-family: "Helvetica Neue", Helvetica, sans-serif;
    font-size: 17px;
    -webkit-tap-highlight-color: transparent;
    -webkit-tap-highlight-color: transparent;
  }
  textarea:focus {
    -webkit-tap-highlight-color: transparent;
    -webkit-tap-highlight-color: transparent;
    -webkit-user-modify: read-write-plaintext-only;
  }
  textarea {
    line-height: 21px;
    width: 100%;
    height: 40px;
    margin-bottom: 15px;
    padding: 10px 15px;
    -webkit-user-select: text;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    outline: 0;
    background-color: #fff;
    -webkit-appearance: none;
  }
  textarea {
    height: auto;
    resize: none;
  }
  .mui-icon {
    font-family: Muiicons;
    font-size: 24px;
    font-weight: 400;
    font-style: normal;
    line-height: 1;
    display: inline-block;
    text-decoration: none;
    -webkit-font-smoothing: antialiased;
  }
  .mui-icon-camera:before {
    content: "\e301";
  }
  .mui-icon-mic:before {
    content: "\e302";
  }
  /*! CSS Used from: Embedded */
  footer {
    position: fixed;
    width: 100%;
    height: 50px;
    min-height: 50px;
    border-top: solid 1px #bbb;
    left: 0px;
    bottom: 0px;
    overflow: hidden;
    padding: 0px 50px;
    background-color: #fafafa;
    z-index: 10;
  }
  .footer-left {
    position: absolute;
    width: 50px;
    height: 50px;
    left: 0px;
    bottom: 0px;
    text-align: center;
    vertical-align: middle;
    line-height: 100%;
    padding: 12px 4px;
  }
  .footer-right {
    position: absolute;
    width: 50px;
    height: 50px;
    right: 0px;
    bottom: 0px;
    text-align: center;
    vertical-align: middle;
    line-height: 100%;
    padding: 12px 5px;
    display: inline-block;
  }
  .footer-center {
    height: 100%;
    padding: 5px 0px;
  }
  .footer-center [class*="input"] {
    width: 100%;
    height: 100%;
    border-radius: 5px;
  }
  .footer-center .input-text {
    background: #fff;
    border: solid 1px #ddd;
    padding: 10px !important;
    font-size: 16px !important;
    line-height: 18px !important;
    font-family: verdana !important;
    overflow: hidden;
  }
  .footer-center .input-sound {
    background-color: #eee;
  }
  footer .mui-icon {
    color: #000;
  }
  footer .mui-icon:active {
    color: #0fc47d !important;
  }
  #msg-sound {
    -webkit-user-select: none !important;
    user-select: none !important;
  }
  footer .mui-icon-paperplane:before {
    content: "发送";
  }
  footer .mui-icon-paperplane {
    font-size: 16px;
    word-break: keep-all;
    line-height: 100%;
    padding-top: 6px;
    color: #0fc47d;
  }
}
</style>
